package com.example.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalTime;

@Component
public class TimeInterceptor implements HandlerInterceptor {

    /**
     * Controller方法执行之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("startTime",System.currentTimeMillis());
        System.out.println("==preHandle==");
        LocalTime now = LocalTime.now();
        int hour = now.getHour();
        if(hour<15)
            throw new RuntimeException("请在16点之后访问");
        return true;//true表示请求放行,继续执行后续操作
    }
    /***
     * 要拦截的Controller方法执行之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        Long startTime=(Long)request.getAttribute("startTime");
        long time=System.currentTimeMillis()-startTime;
        System.out.println("方法耗时:"+time);
    }

}
